package com.wxy.demo.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.wxy.demo.core.PageResult;
import com.wxy.demo.core.QueryPage;
import com.wxy.demo.dao.RequestLogDao;
import com.wxy.demo.entity.RequestLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author e-Xiaoyuan.Wang
 * @since 2022/4/13 14:18
 */
@Transactional
@RestController
@RequestMapping("/request-log")
public class RequestLogController {

    @Autowired
    private RequestLogDao requestLogDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostMapping("/findPage")
    private Object findPage(@RequestBody QueryPage<RequestLog> queryPage) {
        String startTime;
        String endTime;
        RequestLog query = Optional.ofNullable(queryPage.getQueryModel()).orElse(new RequestLog());
        if (StrUtil.isNotBlank(query.getTime()) && query.getTime().contains(",")) {
            String[] split = query.getTime().split(",");
            startTime = split[0];
            endTime = split[1];
        } else {
            String date = DateUtil.format(new Date(), "yyyy-MM-dd");
            startTime = date + " 00:00:00";
            endTime = date + " 23:59:59";
        }
        String sql = "select rl.id,u.name user_name,rl.request_ip,ii.name interface_name,di.name datasource_name,rl.request_time,rl.status,rl.message " +
                "from request_log rl " +
                "left join user u on u.id = rl.user_id " +
                "left join interface_info ii on ii.id = rl.interface_id " +
                "left join data_source_info di on di.id = ii.data_source_id " +
                "where rl.status = ? " +
                "and (u.name like ? " + (StrUtil.isNotBlank(query.getUserName()) ? "" : "or rl.user_id is null") + ") " +
                "and rl.request_ip like ? " +
                "and ii.name like ? " +
                "and di.name like ? " +
                "and rl.request_time between ? and ? " +
                "order by rl.request_time desc " +
                "limit ?, ? ";
        String countSql = "select count(rl.id) from request_log rl " +
                "left join user u on u.id = rl.user_id " +
                "left join interface_info ii on ii.id = rl.interface_id " +
                "left join data_source_info di on di.id = ii.data_source_id " +
                "where rl.status = ? " +
                "and (u.name like ? " + (StrUtil.isNotBlank(query.getUserName()) ? "" : "or rl.user_id is null") + ") " +
                "and rl.request_ip like ? " +
                "and ii.name like ? " +
                "and di.name like ? " +
                "and rl.request_time between ? and ? ";
        List<RequestLog> list = jdbcTemplate.queryForList(sql,
                        query.getStatus(),
                        "%" + Optional.ofNullable(query.getUserName()).orElse("") + "%",
                        "%" + Optional.ofNullable(query.getRequestIp()).orElse("") + "%",
                        "%" + Optional.ofNullable(query.getInterfaceName()).orElse("") + "%",
                        "%" + Optional.ofNullable(query.getDatasourceName()).orElse("") + "%",
                        startTime, endTime,
                        (queryPage.getPageNum() - 1) * queryPage.getPageSize(), queryPage.getPageSize())
                .stream()
                .map(map -> new RequestLog((Long) map.get("id"), (String) map.get("user_name"),
                        (String) map.get("request_ip"), (String) map.get("interface_name"),
                        (String) map.get("datasource_name"), new Date(((Timestamp) map.get("request_time")).getTime()),
                        (Integer) map.get("status"), (String) map.get("message")))
                .collect(Collectors.toList());
        long count = Optional.ofNullable(jdbcTemplate.queryForObject(countSql, Long.class,
                        query.getStatus(),
                        "%" + Optional.ofNullable(query.getUserName()).orElse("") + "%",
                        "%" + Optional.ofNullable(query.getRequestIp()).orElse("") + "%",
                        "%" + Optional.ofNullable(query.getInterfaceName()).orElse("") + "%",
                        "%" + Optional.ofNullable(query.getDatasourceName()).orElse("") + "%",
                        startTime, endTime
                ))
                .orElse(0L);
        return new PageResult<>(list, count / queryPage.getPageSize() + 1, count);
    }
}
